<script setup lang="ts">
import { computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import comScssColor from '@/assets/styles/variables.module.scss'
import { dynamicRoutes, type RouteItem } from '@/router'

import { useStore } from '@/store'
const appStore = useStore().useAppStore()
const layoutStore = useStore().useCustomLayoutStore()

import subMenusItem from './subMensItem.vue'

const router = useRouter()
const route = useRoute()

// 查锁
const mainName = appStore.mainName

const menusRoutes = computed(() => {
  if (!appStore.isLock)
    return appStore.getMenus(
      appStore.getFirstMenu(appStore.transformRoutesKeys())
    )
  else {
    const curMenu = dynamicRoutes.find((x) => x.name === mainName) as RouteItem
    return appStore.getMenus(
      appStore.getFirstMenu(
        appStore.transformRoutesKeys(curMenu?.children || [])
      )
    )
  }
})

// 此处 有一个 bug：
/*
 *  如果 el-sub-menu 的 index 属性绑定的 值 与 el-menu 的 default-active 属性值不一样，会出现 菜单单机两次才会有背景颜色
 *   所以 要保持一致， 最好的办法 都使用 路由的 name 属性值
 */
const defaultActive = computed(
  () => route.matched[route.matched.length - 1].name as string
)

const menuClick = (routes: RouteItem) => {
  router.push({
    name: routes.name
  })
}

defineOptions({
  name: 'Menus'
})
</script>

<template>
  <!-- collapse-transition: 不要使用 自带动画， 会出现  延迟，使用自定义 transtion 自定义动画  -->
  <el-menu
    :active-text-color="comScssColor.activeTextColor"
    :background-color="comScssColor.menusBg"
    :collapse="layoutStore.collapsed"
    :text-color="comScssColor.menuTextColor"
    :collapse-transition="false"
    :default-active="defaultActive"
    v-bind="$attrs"
  >
    <subMenusItem
      :menus="menusRoutes"
      v-if="menusRoutes?.length"
      @click="menuClick"
    />
  </el-menu>
</template>

<style scoped></style>
